package com.example.medicine.View;


import com.example.medicine.Bean.yian.*;
import com.example.medicine.Mapper.yian.*;
import com.example.medicine.Mapper.yonghuMapper;
import com.example.medicine.Mapper.zhenghouMapper;
import com.example.medicine.Mapper.zhengzhuangMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.io.font.PdfEncodings;


import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

@Slf4j
@Controller
public class yianView {

    @Autowired
    private yian_shexiangMapper yian_shexiangMapper;
    @Autowired
    private yian_maizhenMapper yian_maizhenMapper;
    @Autowired
    private zhenghouMapper zhenghouMapper;
    @Autowired
    private zhengzhuangMapper zhengzhuangMapper;
    @Autowired
    private yian_jibingMapper yian_jibingMapper;
    @Autowired
    private yian_jianchaMapper yian_jianchaMapper;
    @Autowired
    private yian_chufangMapper yian_chufangMapper;
    @Autowired
    private yian_cankaoMapper yian_cankaoMapper;
    @Autowired
    private yianMapper yianMapper;
    @Autowired
    private yian_xiyiMapper yian_xiyiMapper;
    @Autowired
    private yian_zhengzhuangMapper yian_zhengzhuangMapper;
    @Autowired
    private yonghuMapper yonghuMapper;
    Subject subject = SecurityUtils.getSubject();
    @RequiresPermissions("文献医案库")
    @RequestMapping("/wxya/create")
    public String wxyaCreateShow(Model model){
        log.info("文献医案创建页面");
        model.addAttribute("yian",new yian());
        return "pages/yian/create";
    }

    @RequiresPermissions("文献医案库")
    @RequestMapping("/wxya/batchAdd")
    public String wxyaBatchShow(){
        log.info("文献医案批量导入页面");
        return "pages/yian/batchAdd";
    }

    @RequiresPermissions("文献医案库")
    @RequestMapping("/wxya")
    public String wxyaList(Model model){
        log.info("文献医案列表页面");
        model.addAttribute("roleType",yonghuMapper.getTypeByUserId(subject.getPrincipal().toString()));
        return "pages/yian/list";
    }

    @RequiresPermissions(value = {"文献医案库","学生录入查询"}, logical = Logical.OR)
    @RequestMapping("/wxya/edit/{yianId}")
    public String getMyxxById(@PathVariable long yianId, Model model) throws Exception{
        log.info("文献医案编辑页面");
        yian yian = yianMapper.getById(yianId);
        List<yian_shexiang> sheList = yian_shexiangMapper.getByYianId(yianId);
        List<yian_maizhen> maiList = yian_maizhenMapper.getByYianId(yianId);
        List<yian_zhengzhuang> zhenghou = yian_zhengzhuangMapper.getByYianId(yianId);  //
        StringBuilder zhBuilder = new StringBuilder();
        if(zhenghou!=null){
            for(yian_zhengzhuang x: zhenghou){
                zhBuilder.append(x.getZhenghou());
            }
        }
        List<yian_jibing> jibing = yian_jibingMapper.getByYianId(yianId);//
        StringBuilder jbBuilder = new StringBuilder();
        if(jibing!=null){
            for(yian_jibing x: jibing){
                jbBuilder.append(x.getMingcheng());
            }
        }
        List<yian_xiyi> xiyiZhenduan = yian_xiyiMapper.getByYianId(yianId);
        StringBuilder xiyibuilder =new StringBuilder();
        if(xiyiZhenduan!=null ){
            for(yian_xiyi x:xiyiZhenduan){
                xiyibuilder.append(x.getName());
            }
        }
        List<yian_jiancha> jiancha = yian_jianchaMapper.getByYianId(yianId);
        List<yian_chufang> chufang = yian_chufangMapper.getByYianId(yianId);
        List<yian_cankao> cankaoList = yian_cankaoMapper.getByYianId(yianId);
        model.addAttribute("yian",yian);
        model.addAttribute("she",sheList);
        model.addAttribute("mai",maiList);
        model.addAttribute("zhenghou",zhBuilder.toString());
        model.addAttribute("jibing",jbBuilder.toString());
        model.addAttribute("xiyiZhenduan",xiyibuilder.toString());
        model.addAttribute("jiancha",jiancha);
        model.addAttribute("chufang",chufang);
        model.addAttribute("cankao",cankaoList);
        model.addAttribute("roleType",yonghuMapper.getTypeByUserId(subject.getPrincipal().toString()));
        return "pages/yian/edit";
    }

    @RequiresPermissions(value = {"文献医案库","学生录入查询"}, logical = Logical.OR)
    @RequestMapping("/wxya/blShow")
    public String blShow(@RequestParam String jiaoshou, @RequestParam String xingming,
                         @RequestParam String nianling, @RequestParam String xingbie,
                         @RequestParam String hunkuang, @RequestParam String time,
                         @RequestParam String detail,@RequestParam String chufang,
                         @RequestParam String chufuzhen,Model model){
        log.info("医案病历预览");
        jiaoshou = jiaoshou + "教授的门诊案例";
        model.addAttribute("jiaoshou",jiaoshou);
        model.addAttribute("xingming",xingming);
        model.addAttribute("nianling",nianling);
        model.addAttribute("xingbie",xingbie);
        model.addAttribute("hunkuang",hunkuang);
        ObjectMapper objectMapper = new ObjectMapper();
        StringBuilder yao = new StringBuilder();
        try {
            List<JsonNode> jsonNodeList = objectMapper.readValue(chufang, new TypeReference<List<JsonNode>>() {});
            for (JsonNode jsonNode : jsonNodeList) {
                String zhongyao = jsonNode.get("zhongyao").asText();
                String yaoliang = jsonNode.get("yaoliang").asText();
                String paozhi = jsonNode.get("paozhi").asText();
                String chandi = jsonNode.get("chandi").asText();
                String beizhu = jsonNode.get("beizhu").asText();
                String daiding = jsonNode.get("daiding").asText();
                yao.append(zhongyao);

                if(!chandi.equals("null")){
                    yao.append(" ").append(chandi);
                }
                if(!yaoliang.equals("null")){
                    yao.append(" ").append(yaoliang);
                }
                if(!daiding.equals("null")){
                    yao.append(" ").append(daiding);
                }
                if(!paozhi.equals("null")){
                    yao.append(" ").append(paozhi);
                }
                if(!beizhu.equals("null")){
                    yao.append(" ").append(beizhu);
                }
                yao.append(" ；");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        chufang = yao.toString();
        String czTime=time,fzTime=time,czDetail=detail,fzDetail=detail,chufang_1=chufang,chufang_2=chufang;
        if(chufuzhen.equals("初诊")){
            fzTime="";
            fzDetail="";
            chufang_2="";
            czDetail=czDetail.equals("。")?"":czDetail;
        }
        else {
            czTime="";
            czDetail="";
            chufang_1="";
            fzDetail=fzDetail.equals("。")?"":fzDetail;
        }
        model.addAttribute("czTime",czTime);
        model.addAttribute("fzTime",fzTime);
        model.addAttribute("czDetail",czDetail);
        model.addAttribute("fzDetail",fzDetail);
        model.addAttribute("chufang",chufang_1);
        model.addAttribute("chufang_2",chufang_2);
        return "pages/yian/bingliShow";
    }

    @RequiresPermissions("文献医案库")
    @RequestMapping("/wxya/createbook")
    public String createShow(@RequestParam String bookName, @RequestParam String zuozhe,
                             @RequestParam String publisher, @RequestParam String edition,
                             @RequestParam String publishTime, @RequestParam String isbn, Model model){
        log.info("文献医案继续录入本书页面");
        yian yian = new yian();
        yian.setShuming(bookName);
        yian.setZuozhe(zuozhe);
        yian.setChubanshe(publisher);
        yian.setChubanshijian(publishTime);
        yian.setBanci(edition);
        yian.setIsbn(isbn);
        model.addAttribute("yian",yian);
        return "pages/yian/create";
    }

    @RequiresPermissions(value = {"文献医案库","学生录入查询"}, logical = Logical.OR)
    @PostMapping(value = "/wxya/generate-pdf", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> generatePdf(@RequestParam("content") String decodedContent, @RequestParam("name") String decodedName) throws IOException {
        log.info("医案PDF导出");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Load the Chinese font (replace with the path to your font file)
        PdfFont chineseFont = PdfFontFactory.createFont("D:\\JavaEE\\IntelliJ IDEA 2022.3.1\\Javaproject\\medicineproject\\medicine\\src\\main\\resources\\static\\font\\SourceHanSerifSC-Regular.otf", PdfEncodings.IDENTITY_H, true);

        PdfWriter pdfWriter = new PdfWriter(baos);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);

        // 应用中文字体
        Paragraph paragraph = new Paragraph(decodedContent).setFont(chineseFont);
        document.add(paragraph);
        document.close();
        pdfDocument.close();

        byte[] pdfBytes = baos.toByteArray();
        baos.close();

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .body(pdfBytes);
    }

}
